package com.jcode.netty.client;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author dreajay
 * @DateTime 2016年12月13日 下午6:26:25
 */
public class MultipleNettyClientMain {

    private static final Logger log = LoggerFactory.getLogger(MultipleNettyClientMain.class);
    private static final AtomicLong count = new AtomicLong(0);

    public static void connectServer(MultipleNettyClient client, String serverIPAddress) {
        try {
            client.connectServer(serverIPAddress);
            log.error("connection size:{}", count.incrementAndGet());
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void runClient(String serverIPAddress) {
        ClientConfig config = new ClientConfig();
        config.setConnectTimeoutMillis(6000000);
        config.setClientWorkerThreads(2);
        config.setClientChannelMaxIdleTimeSeconds(0);// 5秒空闲
        MultipleNettyClient client = new MultipleNettyClient(config);
        client.start();
        connectServer(client, serverIPAddress);
    }

    public static void main(String[] args) throws Exception {
        PropertiesConfiguration prop = new PropertiesConfiguration("config.properties");
        final String serverIp = prop.getString("server.bindIp");
        int start = prop.getInt("server.startPort");
        int end = prop.getInt("server.endPort");

        List<Object> list = prop.getList("server.excludePorts");


        for (int i = start; i <= end; i++) {
            boolean exclude = false;
            for (Object port : list) {
                if (i == Integer.parseInt(port.toString())) {
                    exclude = true;
                }
            }
            if (!exclude) {
                runClient(serverIp + ":" + i);
            }

        }

//        ExecutorService executorService = Executors.newFixedThreadPool(list.size());
//        for (Object port : list) {
//            final String serverIPAddress = serverIp + ":" + port;
//            executorService.execute(new Runnable() {
//                @Override
//                public void run() {
//                    for (int i = 0; i < clientConnectionSize; i++) {
//                        runClient(serverIPAddress);
//                    }
//                }
//            });
//        }

    }
}
